package com.fuze.navi.interceptor;

import com.fuze.navi.common.Advice;
import com.fuze.navi.common.Constant;
import com.fuze.navi.common.NaviException;
import com.fuze.navi.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sepc_
 * @date 3/17/2021 09:32
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final static Integer DATA_LENGTH = 3;

    public final StringRedisTemplate stringRedisTemplate;

    public final UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String uri = request.getRequestURI();
        log.info("request uri = {}", uri);
        // 获取头中token
        String token = request.getHeader(Constant.AUTH_TOKEN);
        log.info("TOKEN = {}", token);
        if (StringUtils.isBlank(token)) {
            throw new NaviException(Advice.TOKEN_MISSING);
        }
        String tokenVal = stringRedisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(tokenVal)) {
            throw new NaviException(Advice.TOKEN_EXPIRED);
        }
        String[] data = tokenVal.split(Constant.DELIMITER);
        if (DATA_LENGTH.equals(data.length)) {
            if (userService.isExist(data[1])) {
                return true;
            }
            throw new NaviException(Advice.TOKEN_VERIFICATION_FAILED);
        }
        return true;
    }

}
